package com.zekdot.registerclient.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zekdot.registerclient.dao.EnrollDataDao;
import com.zekdot.registerclient.dao.EnrollMetaDao;
import com.zekdot.registerclient.dto.Envelope;
import com.zekdot.registerclient.entity.EnrollDataEntity;
import com.zekdot.registerclient.entity.EnrollMetaEntity;
import com.zekdot.registerclient.service.EnrollDataService;
import com.zekdot.registerclient.service.EnrollMetaService;
import com.zekdot.registerclient.util.CheckResult;
import com.zekdot.registerclient.util.IdUtil;
import com.zekdot.registerclient.util.JwtUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

/**
 * Create by zekdot on 20-3-22.
 */
@Service
public class EnrollDataServiceImpl implements EnrollDataService {
    @Resource
    private EnrollDataDao enrollDataDao;
    @Resource
    private EnrollMetaDao enrollMetaDao;
    @Autowired
    private EnrollMetaService enrollMetaService;
    @Autowired
    private AmqpTemplate rabbitTemplate;

    private static String tipTitle[] = {"unchecked","checked","rejected"};
//    @Override
//    public Envelope enrollDataStatus(String eId, String username) {
//        Map<String,Object> statusMap = new HashMap<>();
//        Map<String,Object> res = enrollDataDao.enrollDataStatus(eId,username);
//        statusMap.put("status",-1);
//        if(res == null){
//            return new Envelope(statusMap);
//        }
//        // 获取状态
//        Integer status = (Integer) res.get("status");
//        // 放置状态
//        statusMap.put("status",status);
//        // 获取状态对应的信息
//        String tips = (String) res.get("status_tip");
//        JSONObject jsonObject = JSONObject.parseObject(tips);
//        statusMap.put("statusTip",jsonObject.getString(tipTitle[status]));
//        return new Envelope(statusMap);
//    }

    @Override
    public Envelope enroll(String username,EnrollDataEntity enrollDataEntity) {
        Envelope envelope = enrollMetaService.getEnrollInfo(enrollDataEntity.getEId());
        if(envelope.getCode() != 0)
            return envelope;
        EnrollMetaEntity enrollMetaEntity = (EnrollMetaEntity) envelope.getObj();
        // status状态不为0则说明被终止
        if(enrollDataEntity.getStatus() != 0){
            return new Envelope(2,"报名已被终止",enrollDataEntity.getStatus());
        }
//        enrollDataEntity.setEId(IdUtil.getId());
        enrollDataEntity.setUsername(username);
        Date now = new Date();
        enrollDataEntity.setSubmitTime(new Timestamp(now.getTime()));
        enrollDataEntity.setStatus(0);
        // 如果不需要审核
        if(!enrollMetaEntity.getChecked()){
            enrollDataEntity.setCheckTime(new Timestamp(now.getTime()));
            enrollDataEntity.setStatus(1);
        }
        String str = JSONObject.toJSONString(enrollDataEntity);
        // 存入消息队列
        rabbitTemplate.convertAndSend("EnrollExchange","EnrollRouting", str);
        return Envelope.success;
    }

    @Override
    public Envelope updateStatus(String EId,String userId, String username, int status,String rejectReason) {
        if(status == 0)
            return Envelope.success;
        enrollDataDao.updateStatus(EId,userId,username,status,rejectReason);
        return Envelope.success;
    }

    @Override
    public Envelope getDataByEId(String EId) {
        List<EnrollDataEntity> list = enrollDataDao.getDataByEid(EId);
        return new Envelope(list);
    }

    @Override
    public Envelope addPreEnrollUsers(List<String> usernames, String eId,String userId) {
        EnrollMetaEntity enrollMetaEntity = enrollMetaDao.get(eId);
        if(enrollMetaEntity == null || !enrollMetaEntity.getHost().equals(userId)){
            return new Envelope(1,"您不能在他人的项目下预报名",null);
        }
        List<EnrollDataEntity> list = new ArrayList<>();
        for(String usern:usernames){
            EnrollDataEntity enrollDataEntity = new EnrollDataEntity();
            enrollDataEntity.setContent(null);
            enrollDataEntity.setUsername(usern);
            enrollDataEntity.setEId(eId);
            enrollDataEntity.setCheckTime(null);
            enrollDataEntity.setSubmitTime(null);
            // 状态为预报名
            enrollDataEntity.setStatus(3);
            list.add(enrollDataEntity);
        }
        enrollDataDao.saves(list);
        return Envelope.success;
    }

    @Override
    public Envelope getEnrollResult(String eId, String username) {
        Map<String,Object> map = enrollDataDao.getEnrollResult(eId,username);
        if(map == null){
            map = new HashMap<>();
            map.put("status",-1);
            return new Envelope(map);
        }

        // 获取状态
        Integer status = (Integer) map.get("status");
        // 如果不是预报名状态，需要返回对应的报名提示
        if(status != 3) {
            // 获取状态对应的信息
            String tips = (String) map.get("status_tip");
            JSONObject jsonObject = JSONObject.parseObject(tips);
            map.put("statusTip", jsonObject.getString(tipTitle[status]));
        }else{
            map.put("status",-1);
        }

        map.put("status_tip", null);
        return new Envelope(map);
    }

    @Override
    public Envelope moreEnrollData(String username, Date lastTime, int length) {
        return new Envelope(enrollDataDao.moreEnrollData(username,lastTime,length));
    }

    @Override
    public Envelope getDataDescsByEid(String username, String eId, Date lastTime, int length) {
        return new Envelope(enrollDataDao.getDataDescsByEid(eId,username,lastTime,length));
    }

    @Override
    public Envelope enrollDataDetail(String userId, String username, String eId) {
        return new Envelope(enrollDataDao.enrollDataDetail(userId,username,eId));
    }

    @Override
    public Envelope getEnrollDataByToken(String eId, String token, int length) {
        return new Envelope(enrollDataDao.getEnrollDataByToken(eId,token,length));
    }

    @Override
    public Envelope checkUserByToken(String eId, String reqArrayStr,String token) {
        // 首先核验token
        if(enrollDataDao.validateToken(eId,token) != 1){
            return new Envelope(1,"您的操作令牌有错误",null);
        }
        // 转换json，构造请求消息
        List<Object> reqs = JSONArray.parseArray(reqArrayStr);
        List<Object> list = new ArrayList<>();
        if(reqs.size() == 0){
            return Envelope.success;
        }
        list.add(eId);
        list.add(reqs);
        // 存入消息队列
        rabbitTemplate.convertAndSend("UpdateExchange","UpdateRouting",list);
        return Envelope.success;
    }

    @Override
    public Envelope getExcelData(String tempToken) {
        CheckResult checkResult = JwtUtil.validateJWT(tempToken);
        if(!checkResult.isSuccess()){
            return new Envelope(1,"无效的token，可能是时间已经过期",null);
        }
        Map<String,Object> map = checkResult.getClaims();
        String eId = (String) map.get("eId");

        return new Envelope(enrollDataDao.getExcelData(eId));
    }
}
